#!/bin/bash
# description: Install X11vnc server for UOS desktop professional
# version: 0.0.1
# author: ZhangChiQian<zhangchiqian@uniontech.com>
# date: 2021-5-13

echo "+------------------------------------------+"
echo "|   开始安装v11vnc		                  "
echo "|   安装过程中要多次输入管理员密码，请保持耐心 " 
echo "+------------------------------------------+"

if [ $USER == 'root' ];then
    UserHome='/root'
else
    UserHome="/home/$USER"
fi

dpkg -l x11vnc &>/dev/null
if [ $? -eq 0 ];then
    echo "x11vnc已经安装"
else
    echo "正在安装x11vnc"        
    sudo dpkg -i ./x11vnc*.deb
fi

if [ $? -ne 0 ];then
    echo "修复依赖关系"
    echo -e "\033[40;37m 是否使用离线依赖包修复依赖关系？(y/n) \033[0m"
    read  i
	case $i in
		n|N)
            echo -e "\033[40;37m 是否尝试使用仓库修复依赖关系？(y/n) \033[0m"
            read j
            case $j in 
                y|Y)
                    echo "正在使用仓库修复依赖关系："
			        sudo apt --fix-broken install
                    ;;
                n|N)
                    echo -e "\033[40;37m 选择不修复依赖关系，按任意键结束安装 \033[0m"
                    read j
                    exit 11
                    ;;
            esac
			;;	
		y|Y)
			echo "尝试使用离线依赖包修复依赖关系"
			sudo dpkg -i ./Dependent/*.deb 
			;;
		*)
			echo "输入错误，退出"
			exit 11 
			;;
	esac
fi

echo -e "\033[40;37m 请设置连接vnc桌面时的密码（输入两次） \033[0m"
declare -i n=0
x11vnc -storepasswd 
while [ $? -ne 0 ];do
    echo -e "\033[0;31m 两次密码输入不匹配，请重新设置！ \033[0m"
    if [ $n -gt 5 ];then
        echo -e "\033[0;31m 错误次数过多，安装失败！ \033[0m"
        echo -e "\033[40;37m 安装失败，按任意键退出 \033[0m"
        read i
        exit 11
    fi
    let n++
    x11vnc -storepasswd 
done

if [ ! -e ~/.vnc/passwd ];then
    echo -e "\033[40;37m 安装失败，按任意键退出 \033[0m"
    read i
    exit 11
fi

echo "设置x11vnc自启动服务"
cat > ./x11vnc.service << EOF
[Unit]
Description=Start x11vnc at startup
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/x11vnc -auth /var/run/lightdm/root/:0  -forever -loop -noxdamage -repeat -rfbauth $UserHome/.vnc/passwd -rfbport 5900 -shared
ExecStop=/usr/bin/killall x11vnc
[Install]
WantedBy=multi-user.target
EOF

sudo mv ./x11vnc.service /lib/systemd/system/x11vnc.service

sudo systemctl daemon-reload
sudo systemctl enable x11vnc
sudo systemctl start x11vnc

if [ $? -eq 0 ];then
    echo -e "\033[40;37m 安装完成，按任意键退出 \033[0m"
    read i
    exit 0
fi